#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QMessageBox>
#include <QNetworkDatagram>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    // 创建socket对象
    socket  = new QUdpSocket(this);
    // 设置窗口标题
    this->setWindowTitle("服务器");
    // 先链接信号槽
    connect(socket, &QUdpSocket::readyRead, this, &Widget::processRequest);
    // 后绑定端口号
    bool ret = socket->bind(QHostAddress::Any, 8888);
    if (!ret) {
        // 绑定失败
        // 弹出一个对话框。告诉用户绑定失败
        QMessageBox::critical(this, "服务器启动出错!!", socket->errorString());
        return;
    }

}

Widget::~Widget()
{
    delete ui;
}

void Widget::processRequest()
{
    // 1、读取请求并解析
    const QNetworkDatagram& requestDatagram = socket->receiveDatagram(); // 获取数据包
    QString request = requestDatagram.data(); // 提取出有效数据
    // 2、根据请求计算响应
    const QString& response = process(request);
    // 3、把响应写回给客户端
    QNetworkDatagram responseDatagram(response.toUtf8(), requestDatagram.senderAddress(), requestDatagram.senderPort());
    // 发送响应数据包
    socket->writeDatagram(responseDatagram);
    // 把这次交互的信息显示到界面上
    QString log = "[" + requestDatagram.senderAddress().toString() + " : " + QString::number(requestDatagram.senderPort()) + "]: request: " + request + " , response: " + response;
    ui->listWidget->addItem(log);
}

QString Widget::process(QString &request)
{
    return request;
}

